package service

import (
	"jslog/system/middleware"
	"net"
	"net/http"
	"strings"

	"jslog/common"

	"github.com/gin-gonic/gin"
)

type Comon struct {
	common.Comm
}

func (l *Comon) Json(code int, data interface{}, status string, message string, c *gin.Context) {

	if code == 0 {
		code = 200
	}

	c.JSON(http.StatusOK, gin.H{
		"code":   code,
		"data":   data,
		"status": status,
		"msg":    message,
	})
}

func (l *Comon) Succee(data interface{}, c *gin.Context) {

	l.Json(200, data, "succee", "", c)
}

func (l *Comon) Error(code int, data interface{}, msg string, c *gin.Context) {

	if code == 0 {
		code = -1
	}

	if msg == "" {
		msg = "数据错误"
	}
	l.Json(code, data, "error", msg, c)
}

func GetClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	if index := strings.Index(xForwardedFor, ", "); index >= 0 {
		// 如果有多个IP地址，则取第一个IP地址
		// 例如: X-Forwarded-For: client, proxy1, proxy2
		return strings.TrimSpace(xForwardedFor[:index])
	}
	if xForwardedFor != "" {
		return xForwardedFor
	}

	xRealIP := r.Header.Get("X-Real-IP")
	if xRealIP != "" {
		return xRealIP
	}

	if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		return ip
	}
	return r.RemoteAddr
}

type NoVerify struct {
	Comon
}

func (s *NoVerify) Json(code int, data interface{}, status string, message string, c *gin.Context) {
	if code == 0 {
		code = 200
	}
	c.JSON(http.StatusOK, gin.H{
		"code":   code,
		"data":   data,
		"status": status,
		"msg":    message,
	})
}

func (s *NoVerify) Succee(data interface{}, c *gin.Context) {
	s.Json(200, data, "succee", "", c)
}

func (s *NoVerify) Error(code int, data interface{}, msg string, c *gin.Context) {
	if code == 0 {
		code = -1
	}
	if msg == "" {
		msg = "数据错误"
	}
	s.Json(code, data, "error", msg, c)
}

type Verify struct {
	Comon
}

func (s *Verify) GetUserInfo(c *gin.Context) (*middleware.Claims, error) {
	reTokan, err := middleware.GetInfo(c)
	if err == nil {
		return reTokan, nil
	}
	return nil, err
}
